package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zx
 * @date 2021/11/29 10:50
 */
@Service
@Slf4j
public class CommentServiceImpl  implements CommentService {

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    CommentService commentService;

    @Autowired
    CommentHotService commentHotService;

    /**
     * 发表评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        // 1. 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        // 1.1校验是否登录
        if (user != null) {
            ResponseResult<ApUser> userLogin = userFeign.findUserById(user.getId());

            //校验内容不为空
            if (userLogin.getCode() != 0 && userLogin.getData() == null) {
                log.error("当前登录信息有误");
                CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            user = userLogin.getData();

            //创建评论信息
            ApComment apComment = new ApComment();

            apComment.setAuthorId(user.getId());
            apComment.setAuthorName(user.getName());
            apComment.setArticleId(dto.getArticleId());
            apComment.setType((short) 0);
            apComment.setChannelId(0);
            apComment.setContent(dto.getContent());
            apComment.setImage(user.getImage());
            apComment.setLikes(0);
            apComment.setReply(0);
            apComment.setFlag((short) 0);
            apComment.setOrd(0);
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());

            //4. ，并保存到mongo
            mongoTemplate.save(apComment);
            System.out.println("评论成功");
            return ResponseResult.okResult();

        }
        return null;
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {

//        1. 参数校验
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("当前无用户");
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        评论id不能为空  operation必须为 0  或  1
//        2. 根据评论id查询评论数据， 为返回错误信息
        ApComment byId = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (byId == null) {
            log.error("当前无评论");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        3. 如果是点赞操作 判断是否已经点赞
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
        ApCommentLike like = mongoTemplate.findOne(query, ApCommentLike.class);
        Short operation = dto.getOperation();
        if (like == null) {
            log.info("开始点赞操作");
            if (operation.intValue() == 0) {
                //        未点过赞   保存点赞信息到mongo
                log.info("点赞");
                //        并修改评论信息的点赞数量( + 1)
                byId.setLikes(byId.getLikes() + 1);
                mongoTemplate.save(byId);
                if (byId.getLikes() >=10 && byId.getFlag().shortValue()==0 ){
                    commentHotService.hotCommentExecutor(byId);
                }

                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(byId.getContent());
                apCommentLike.setOperation(dto.getOperation());

                mongoTemplate.save(apCommentLike);

            } else {
                //        4. 如果是取消点赞操作
                if (byId.getLikes() < 0) {
                    //要判断下别减成负数
                    log.error("点赞数不足以取消点赞");
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
                }

                // 并修改评论信息的点赞数量( - 1)
                byId.setLikes(byId.getLikes() - 1);
                mongoTemplate.save(byId);
                //删除点赞信息
                mongoTemplate.remove(query, ApCommentLike.class);

            }
        } else {
            //        点过赞提示 请勿重复点赞
            log.error("请勿重复点赞");
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
        }

        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        Map<String, Object> map = new HashMap<>();
        map.put("likes", byId.getLikes());
        System.out.println("点赞/取消点赞成功");
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
//        1. 参数校验
        log.info("校验文章id");
        if (dto == null||dto.getArticleId() == null) {
            log.error("缺少参数");
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "缺少参数");
        }

        log.info("校验size");
        Integer size = dto.getSize();
//        if (dto.getSize()==null ||dto.getSize() <= 0) {
//            dto.setSize(10);
//        }
        if (size==null ||size <= 0) {
            dto.setSize(10);
        }
        size = dto.getSize();

        log.info("根据条件查询评论列表");
//        List<ApComment> apCommentList = mongoTemplate.find(
//                Query.query(Criteria.where("articleId").is(dto.getArticleId())
//                        .and("createdTime").lt(dto.getMinDate()))
//                        .limit(dto.getSize())
//                        .with(Sort.by(Sort.Direction.DESC, "createdTime")),
//                ApComment.class
//        );

        List<ApComment> apCommentList = null;

        if(dto.getIndex().intValue() == 1){ // 文章评论的首页
            //查询热点评论  5
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes"));
            apCommentList = mongoTemplate.find(query, ApComment.class);
            // 热点集合不为空
            if (CollectionUtils.isNotEmpty(apCommentList)) {
                size = size - apCommentList.size();
                List<ApComment> normalComments = mongoTemplate.find(getQuery(dto, size), ApComment.class);
                apCommentList.addAll(normalComments);
            }else {
                apCommentList = mongoTemplate.find(
                        getQuery(dto,size),
                        ApComment.class
                );
            }
        }else {
            apCommentList = mongoTemplate.find(
                    getQuery(dto,dto.getSize()),
                    ApComment.class
            );
        }

        log.info("判断当前用户是否登录");
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("未登录直接返回评论列表");
            return ResponseResult.okResult(apCommentList);
        }

        log.info("查看评论人");

        List<ApCommentVo> apCommentVoList = new ArrayList<>();

        List<String> list = apCommentList.stream().map(comment -> comment.getId()).collect(Collectors.toList());

        log.info(" 查询 点赞批量列表 按照评论id 筛选");
        Query commentList = Query.query(Criteria.where("commentId").in(list).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(commentList, ApCommentLike.class);

        // 遍历当前用户点赞列表 和当前评论列表
        if(CollectionUtils.isNotEmpty(apCommentList)
                && CollectionUtils.isNotEmpty(apCommentLikes)){
            apCommentList.forEach(comment ->{ //遍历所有文章列表ID
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment, apCommentVo);
                //遍历当前用户点赞列表
                apCommentLikes.forEach(apCommentLike ->{
                    // 文章评论列表id 和 当前用户点赞评论列表id是否相等
                    if (comment.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                    }
                });
                apCommentVoList.add(apCommentVo);
            });
            return ResponseResult.okResult(apCommentVoList.stream().sorted((o1, o2) -> o2.getLikes() - o1.getLikes()).collect(Collectors.toList()));
        }
        return ResponseResult.okResult(apCommentList.stream().sorted((o1, o2) -> o2.getLikes() - o1.getLikes()).collect(Collectors.toList()));
    }


    /**
     * 构建查询条件
     */
    private Query getQuery(CommentDTO dto, Integer size) {
        System.out.println("dto = " + dto + ", size = " + size);
        return Query.query(Criteria.where("articleId").is(dto.getArticleId())
                .and("flag").is(0).and("createdTime").lt(dto.getMinDate()))
                .limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
    }
}

